const express=require('express');
const router = express.Router();
const pro =require("../sql/pro");
const banner=require("../sql/banner");
const user=require("../sql/user");
const cart=require("../sql/cart");
const order=require("../sql/order");
const search=require("../sql/search");
const sql = require("../sql/sql");
const rn= require("randomnumber");
const tools = require('../tools');
const uuid=require("uuid");
const md5= require("md5");
const jwt = require("jsonwebtoken");
const { log } = require('debug');

router.get('/',function(req,res,data){
    res.send('api')
});

/**
* @apiGroup 商品信息
* @api {get} /api/Get/pro 获取商品数据
* @apiVersion 0.0.0
* @apiDescription 分页请求商品数据
* @apiParam {String} sKey="" 要搜索的关键字
* @apiSuccess {number} code 请求状态
* @apiSuccess {string} title 请求说明
* @apiSuccess {array} msg 请求数据
* @apiSuccessExample {json} Success-Response:
* {
*    "code":200,
*    "title":"请求成功",
*    "msg":[{},{},...]
* }
* @apiError {number} code 请求状态
* @apiError {string} title 请求说明
* @apiError {array} msg 请求数据
* @apiErrorExample {json} Error-Response:
* {
*    "code":400,
*    "title":"请求失败",
*    "msg":"NOT DATA"
* }
* @apiSampleRequest http://localhost:5000/api/Get/pro
*/
router.get('/Get/pro',function(req,res,data){
    let proName=new RegExp(req.query.sKey) || { };

    sql.getData(pro,{proName}).then(data=>{
        res.send({
            code:200,
            title:"请求成功",
            msg:data
        }) 
    }).catch(()=>{
        res.send({
            code:400,
            title:"请求失败",
            msg:"NOT DATA"
        })
    })  
})

/**
* @apiGroup 商品信息
* @api {get} /api/Get/pro/detail 获取商品详情数据
* @apiVersion 0.0.0
* @apiDescription 请求指定商品详情数据，嘿嘿
* @apiParam {String} id="" 要获取的商品详情的商品id
* @apiSuccess {number} code 请求状态
* @apiSuccess {string} title 请求说明
* @apiSuccess {array} msg 请求数据
* @apiSuccessExample {json} Success-Response:
* {
*    "code":200,
*    "title":"请求成功",
*    "msg":{}
* }
* @apiError {number} code 请求状态
* @apiError {string} title 请求说明
* @apiError {array} msg 请求数据
* @apiErrorExample {json} Error-Response:
* {
*    "code":204,
*    "title":"请求失败",
*    "msg":"NOT DATA"
* }
* @apiSampleRequest http://localhost:5000/api/Get/pro/detail
*/

// 获取商品详情的接口
router.get('/Get/pro/detail', function(req, res, next) {
    sql.getData(pro,{proId:req.query.id}).then(data=>{
        res.send({
            code:200,
            title:"请求成功",
            msg:data[0]
        })
    }).catch(err=>{
        res.send({
            code:204,
            title:"请求失败",
            msg:"NOT DATA"
        })
    });
});

/**
* @apiGroup 商品信息
* @api {get} /api/Get/pro/page 获取指定分页数据
* @apiVersion 0.0.0
* @apiDescription 获取指定分页数据
* @apiParam {Number} num=10 单页要显示的数据条数，默认单页10条
* @apiParam {Number} index=0 查询的页码，默认为0，表示第一页
* @apiSuccess {number} code 请求状态
* @apiSuccess {string} title 请求说明
* @apiSuccess {array} msg 请求数据
* @apiSuccessExample {json} Success-Response:
    res.send({
        code:200,
        title:"请求成功",
        msg:data
    })
* @apiSampleRequest http://localhost:5000/api/Get/pro/page
*/

// 获取指定分页数据
router.get('/Get/pro/page', function(req, res, next) {
    let num = req.query.num-0 || 10;
    let index = req.query.index * 1 || 0;
    sql.getPageData(pro, num, index).then(data=>{
        res.send({
            code:200,
            title:"请求成功",
            msg:data
        })
    });
});

/**
* @apiGroup 商品信息
* @api {get} /api/Get/pro/sort 获取根据指定字段排序数据
* @apiVersion 0.0.0
* @apiDescription 获取根据指定字段排序数据
* @apiParam {String} col="price" 要排序的字段
* @apiParam {Number} direct=1 升序或降序，1表示升，-1表示降
* @apiSuccess {number} code 请求状态
* @apiSuccess {string} title 请求说明
* @apiSuccess {array} msg 请求数据
* @apiSuccessExample {json} Success-Response:
    res.send({
        code:200,
        title:"请求成功",
        msg:data
    })
* @apiSampleRequest http://localhost:5000/api/Get/pro/sort
*/

// 根据指定字段排序
router.get('/Get/pro/sort', function(req, res, next) {

    
    let col=req.query.col || "price";
    let direct= req.query.direct || 1;

    var o = {};
    o[col] = direct / 1;

    sql.getSortData(pro, o).then(data=>{
        res.send({
            code:200,
            title:"请求成功",
            msg:data
        })
    });
});

/**
* @apiGroup 商品信息
* @api {get} /api/Get/pro/kind 获取商品分类
* @apiVersion 0.0.0
* @apiDescription 获取商品分类
* @apiSuccess {number} code 请求状态
* @apiSuccess {string} title 请求说明
* @apiSuccess {array} msg 请求数据
* @apiSuccessExample {json} Success-Response:
* {
*    "code":200,
*    "title":"请求成功",
*    "msg":[{},{},...]
* }
* @apiError {number} code 请求状态
* @apiError {string} title 请求说明
* @apiError {array} msg 请求数据
* @apiErrorExample {json} Error-Response:
* {
*    "code":400,
*    "title":"请求失败",
*    "msg":"NOT DATA"
* }
* @apiSampleRequest http://localhost:5000/api/Get/pro/kind
*/
router.get('/Get/pro/kind',function(req,res,data){
    sql.getKind(pro,"kind").then(data=>{
        res.send({
            code:200,
            title:"请求成功",
            msg:data
        })
    }).catch(()=>{
        res.send({
            code:400,
            title:"请求失败",
            msg:"NOT DATA"
        })
    })  
})

/**
* @apiGroup 商品信息
* @api {get} /api/Get/pro/brand 根据商品分类获取品牌信息
* @apiVersion 0.0.0
* @apiDescription 根据商品分类获取品牌信息
* @apiParam {String} kindKey 分类名称
* @apiSuccess {number} code 请求状态
* @apiSuccess {string} title 请求说明
* @apiSuccess {array} msg 请求数据
* @apiSuccessExample {json} Success-Response:
    res.send({
        code:200,
        title:"请求成功",
        msg:data
    })
* @apiSampleRequest http://localhost:5000/api/Get/pro/brand
*/

router.get('/Get/pro/brand', function(req, res, next) {
    let kindKey = req.query.kindKey

    sql.getData(pro, {kind: kindKey}).then(data=>{
        let msg = [];       // [{brand},{brand}]

        data.forEach(val => {
            msg.push({
                brandId: 'brand-'+uuid.v1(),
                brand: val.brand,
                logo: val.logo
            })
        });

        var newMsg = [];
        msg.forEach(val=>{
            if(!has(newMsg, val.brand)){
                newMsg.push(val)
            }
        })

        res.send({
            code:200,
            title:"获取成功",
            msg:newMsg
        })

        function has(arr, key){
            return arr.some(val=>{
                return val.brand === key
            })
        }

    });
});

/**
* @apiGroup 轮播图信息
* @api {get} /api/Get/banner 获取轮播图信息
* @apiVersion 0.0.0
* @apiDescription 获取轮播图信息
* @apiSuccess {number} code 请求状态
* @apiSuccess {string} title 请求说明
* @apiSuccess {array} msg 请求数据
* @apiSuccessExample {json} Success-Response:
* {
*    "code":200,
*    "title":"请求成功",
*    "msg":[{},{},...]
* }
* @apiError {number} code 请求状态
* @apiError {string} title 请求说明
* @apiError {array} msg 请求数据
* @apiErrorExample {json} Error-Response:
* {
*    "code":400,
*    "title":"请求失败",
*    "msg":"NOT DATA"
* }
* @apiSampleRequest http://localhost:5000/api/Get/banner
*/
router.get('/Get/banner',function(req,res,data){
    sql.getData(banner).then(data=>{
        res.send({
            code:200,
            title:"请求成功",
            msg:data
        })
    }).catch(()=>{
        res.send({
            code:400,
            title:"请求失败",
            msg:"NOT DATA"
        })
    })  
})



/**
* @apiGroup 用户信息管理
* @api {get} /api/Get/user/send 发送短信验证码
* @apiVersion 0.0.0
* @apiDescription 根据手机号发送短信验证码
* @apiParam {Number} tel 手机号
* @apiSuccess {number} code 请求状态
* @apiSuccess {string} title 请求说明
* @apiSuccess {array} msg 请求数据
* @apiSuccessExample {json} Success-Response:
    res.send({
        code:200,
        title:"请求成功",
        msg:data
    })
* @apiSampleRequest http://localhost:5000/api/Get/user/send
*/

router.get('/Get/user/send',function(req,res,next){
    let tel = req.query.tel*1;
    let code = rn.generate(6);

    sql.getData(user,{tel}).then(data=>{
        if(data.length>0){
            if(data.username && data.password){
                res.send({
                    code:202,
                    title:'手机号已被注册',
                    msg:'无'
                })
            }else{
                tools.sendMsg(tel,code).then(result=>{
                    sql.setData(user,{tel},{code}).then(()=>{
                        res.send({
                            code:201,
                            title:'验证码再次发送成功',
                            msg:code
                        })
                    })    
                }).catch(err=>{
                    res.send({
                        code:203,
                        title:err.data.Message,
                        msg:'无'
                    })
                }) 
            }
        }else{
            tools.sendMsg(tel,code).then(result=>{
                sql.addData(user,{tel,code}).then(()=>{
                    res.send({
                        code:200,
                        title:'验证码发送成功',
                        msg:code
                    })
                })    
            }).catch(err=>{
                res.send({
                    code:203,
                    title:"请输入正确的手机号码",
                    msg:'无'
                })
            }) 
        }
    })
})


/**
* @apiGroup 用户信息管理
* @api {post} /api/Post/user/register 注册
* @apiVersion 0.0.0
* @apiDescription 注册
* @apiParam {string} username 账号
* @apiParam {string} password 密码
* @apiParam {Number} tel 手机号
* @apiParam {Number} code 验证码
* @apiSuccess {number} code 请求状态
* @apiSuccess {string} title 请求说明
* @apiSuccess {array} msg 请求数据
* @apiSuccessExample {json} Success-Response:
    res.send({
        code:200,
        title:"请求成功",
        msg:data
    })
* @apiSampleRequest http://localhost:5000/api/Post/user/register
*/

router.post('/Post/user/register',function(req,res,next){
    let userName=req.body.username;
    let passWord=req.body.password;
    let tel=req.body.tel*1;
    let code=Number(req.body.code);
    let v1 = uuid.v1();
    sql.getData(user,{userName}).then(data1=>{
        
            sql.getData(user,{tel}).then(data2=>{
                if(data2.length>0){
                    if(data2[0].userName){
                        res.send({
                            code:203,
                            title:'一个手机号只能注册一个账号',
                            msg:'无'
                        })
                    }else{
                        if(code !== data2[0].code){
                            res.send({
                                code:204,
                                title:"验证码错误",
                                msg:"无"
                            })
                        }else{
                            sql.setData(user,{tel},{
                                userId:v1,
                                userName,
                                passWord:md5(passWord),
                                tel,
                                registerTime:Date.now(),
                                power:0,
                                isLogin:0,
                                nickName:"临时用户"
                            }).then(()=>{
                                res.send({
                                    code:200,
                                    title:'注册成功',
                                    msg:'无'
                                })
                            })
                        }
                    }
                    
                }else{
                    res.send({
                        code:202,
                        title:"请先发送验证码",
                        msg:"无"
                    })
                }
            })
        
    })
})

/**
* @apiGroup 用户信息管理
* @api {post} /api/Post/user/login 登陆
* @apiVersion 0.0.0
* @apiDescription 登陆
* @apiParam {string} username 账号
* @apiParam {string} password 密码
* @apiParam {Number} tel 手机号
* @apiSuccess {number} code 请求状态
* @apiSuccess {string} title 请求说明
* @apiSuccess {array} msg 请求数据
* @apiSuccessExample {json} Success-Response:
    res.send({
        code:200,
        title:"请求成功",
        msg:data
    })
* @apiSampleRequest http://localhost:5000/api/Post/user/login
*/
router.post('/Post/user/login',function(req,res,next){
    let userName=req.body.username;
    let passWor=req.body.password;
    let tel=req.body.tel?req.body.tel*1: '';
    sql.getData(user,{$or:[{userName},{tel}]}).then(data=>{
        console.log(data);
        if(data.length<1){
            res.send({
                code:201,
                title:"该账号或手机号未注册",
                msg:"无"
            })
        }else{
            if(md5(passWor) == data[0].passWord){
                sql.setData(user,{$or:[{userName},{tel}]},{
                    lastTime:Date.now(),
                    isLogin:1
                }).then(()=>{
                    const token=jwt.sign({
                        userId: data.userId
                    }, "横扫千军", {
                        expiresIn: 60 * 60 * 2
                    })
                    res.send({
                        code:200,
                        title:"登录成功",
                        msg:data[0].userId,
                        token
                    })
                })
            }else{
                res.send({
                    code:202,
                    title:"密码不正确",
                    msg:"无"
                })
            }
        }
    })
})


/**
* @apiGroup 用户信息管理
* @api {post} /api/Post/user/msg 获取用户信息
* @apiVersion 0.0.0
* @apiDescription 获取用户信息
* @apiParam {string} userId 用户ID
* @apiParam {string} token 用户登陆状态
* @apiSuccess {number} code 请求状态
* @apiSuccess {string} title 请求说明
* @apiSuccess {array} msg 请求数据
* @apiSuccessExample {json} Success-Response:
    res.send({
        code:200,
        title:"请求成功",
        msg:data
    })
* @apiSampleRequest http://localhost:5000/api/Post/user/msg
*/
router.post('/Post/user/msg',function(req,res,next){
    let userId=req.body.userId;
    let token=req.headers.token;
    jwt.verify(token,"横扫千军",(err,data1)=>{
        if(err){
            res.send({
                code:400,
                title:"登录信息失效，请重新登录",
                msg:err
            })
        }else{
            sql.getData(user,{userId}).then(data2=>{
                res.send({
                    code:200,
                    title:'获取成功',
                    msg:data2
                })
            })
        }
    })
})


/**
* @apiGroup 用户信息管理
* @api {post} /api/Post/user/exit 退出
* @apiVersion 0.0.0
* @apiDescription 退出
* @apiParam {string} userId 用户ID
* @apiParam {string} token 用户登陆状态
* @apiSuccess {number} code 请求状态
* @apiSuccess {string} title 请求说明
* @apiSuccess {array} msg 请求数据
* @apiSuccessExample {json} Success-Response:
    res.send({
        code:200,
        title:"请求成功",
        msg:data
    })
* @apiSampleRequest http://localhost:5000/api/Post/user/exit
*/
router.post('/Post/user/exit',function(req,res,next){
    let userId=req.body.userId;
    let token=req.headers.token;
    jwt.verify(token,"横扫千军",(err,data)=>{
        if(err){
            res.send({
                code:400,
                title:"登录信息失效，请重新登录",
                msg:err
            })
        }else{
            sql.setData(user,{userId},{isLogin:0}).then(()=>{ 
                res.send({
                    code:200,
                    title:"退出成功",
                    msg:"无"
                })
            })
        }
    })
})


/**
* @apiGroup 购物车信息
* @api {post} /api/Post/cart/add 添加购物车数据
* @apiVersion 0.0.0
* @apiDescription 添加购物车数据
* @apiParam {String} userId 要添加购物车数据的用户id
* @apiParam {String} proId 要添加到购物车的商品id
* @apiParam {Number} num 数量
* @apiSuccess {number} code 请求状态
* @apiSuccess {string} title 请求说明
* @apiSuccess {array} msg 请求数据
* @apiSuccessExample {json} Success-Response:
    res.send({
        code:200,
        title:"首次添加购物车成功",
        msg:"ok"
    })
    res.send({
        code:201,
        title:"更新购物车成功",
        msg:"ok"
    })
    res.send({
        code:202,
        title:"商品不存在",
        msg:"no"
    })
* @apiSampleRequest http://localhost:5000/api/Post/cart/add
*/
router.post('/Post/cart/add',function(req,res,next){
    let userId = req.body.userId
    let proId = req.body.proId
    let num = req.body.num*1
    let token = req.headers.token
    console.log(12311,token);
    tools.verify(token).then(result => {
        // console.log('token is ok');
        sql.getData(pro, {proId}).then(pd=>{
            if(pd.length > 0){
                sql.getData(cart, {userId}).then(data=>{
                    if(data.length < 1){
                        sql.addData(cart, {
                            cartId: uuid.v1(),
                            userId: userId,
                            proData: [{
                                proId:proId,
                                num:num,
                                img:pd[0].img,
                                proName:pd[0].proName,
                                price:pd[0].price,
                                flag:1
                            }]
                        }).then(()=>{
                            res.send({
                                code:200,
                                title:"首次添加购物车成功",
                                msg:"ok"
                            })
                        })
                    }else{
                        let arr = data[0].proData
                        let i = 0;
                        let onoff = arr.some((val,idx)=>{
                            i = idx
                            return val.proId === proId
                        })
                        if(onoff){
                            arr[i].num += Number(num)
                        }else{
                            arr.push({
                                proId:proId,
                                num:num,
                                img:pd[0].img,
                                proName:pd[0].proName,
                                price:pd[0].price,
                                flag:1
                            })
                        }
                        sql.setData(cart, {userId}, {
                            proData: arr
                        }).then(()=>{
                            res.send({
                                code:201,
                                title:"更新购物车成功",
                                msg:"ok"
                            })
                        })
                    }
                })
            }else{
                res.send({
                    code:202,
                    title:"商品不存在",
                    msg:"no"
                })
            }
        })
    }).catch(err=>{
        console.log('失败了',err);
        res.send({
            code:400,
            title:"登录信息失效，请重新登录",
            msg:err
        })
    })
})

/**
* @apiGroup 购物车信息
* @api {post} /api/Post/cart 获取购物车数据
* @apiVersion 0.0.0
* @apiDescription 获取购物车数据
* @apiParam {String} userId 要添加购物车数据的用户id
* @apiSuccess {number} code 请求状态
* @apiSuccess {string} title 请求说明
* @apiSuccess {array} msg 请求数据
* @apiSuccessExample {json} Success-Response:
    res.send({
        code:200,
        title:"成功获取数据",
        msg:"ok"
    })
    res.send({
        code:400,
        title:"登录信息失效，请重新登录",
        msg:"ok"
    })
    
* @apiSampleRequest http://localhost:5000/api/Post/cart
*/
router.post('/Post/cart',function(req,res,next){
    let userId = req.body.userId
    let token = req.headers.token
    tools.verify(token).then(result => {
        sql.getData(cart,{userId}).then(data=>{
            let d =data[0]?data[0]:{}
            res.send({
                code:200,
                title:"成功获取数据",
                msg: d
            })
        })
    }).catch(err=>{
        res.send({
        code:400,
        title:"登录信息失效，请重新登录",
        msg:err
        })
    })
})


/**
* @apiGroup 购物车信息
* @api {post} /api/Post/cart/del 删除购物车内的商品数据
* @apiVersion 0.0.0
* @apiDescription 删除购物车内的商品数据
* @apiParam {String} userId 要修改购物车数据的用户id
* @apiParam {String} proId 要修改购物车的商品数据的id
* @apiSuccess {number} code 请求状态
* @apiSuccess {string} title 请求说明
* @apiSuccess {array} msg 请求数据
* @apiSuccessExample {json} Success-Response:
    res.send({
        code:200,
        title:"删除成功",
        msg:data
    })
    res.send({
        code:400,
        title:"登录信息失效",
        msg:err
    })
* @apiSampleRequest http://localhost:5000/api/Post/cart/del
*/
router.post('/Post/cart/del',function(req,res,next){
    let userId = req.body.userId
    let proId = req.body.proId
    let token = req.headers.token
    tools.verify(token).then(result => {
        console.log(11122);
        sql.getData(cart,{userId}).then(data=>{
            if(data.length > 0){
                let arr = data[0].proData
                let i = 0;
                let onoff = arr.some((val,idx)=>{
                    i = idx
                    return val.proId === proId
                })
                if(onoff){
                    arr.splice(i, 1)
                }
                sql.setData(cart, {userId}, {
                    proData: arr
                }).then(()=>{
                    sql.getData(cart, {userId}).then(cartData=>{
                        res.send({
                            code:200,
                            title:"删除成功",
                            msg:cartData[0]
                        })
                    })
                })
            }else{
                res.send({
                    code:201,
                    title:"没有购物车数据",
                    msg:"no"
                })
            }
        })
    }).catch(err => {
        res.send({
            code:400,
            title:"登录失效",
            msg:err
        })
    })
})

/**
* @apiGroup 购物车信息
* @api {post} /api/Post/cart/num 修改购物车内的商品数量
* @apiVersion 0.0.0
* @apiDescription 修改购物车内的商品数量
* @apiParam {String} userId 要修改购物车数据的用户id
* @apiParam {String} proId 要修改购物车的商品数据的id
* @apiParam {number} num 要修改购物车的商品数量
* @apiSuccess {number} code 请求状态
* @apiSuccess {string} title 请求说明
* @apiSuccess {array} msg 请求数据
* @apiSuccessExample {json} Success-Response:
    res.send({
        code:200,
        title:"删除成功",
        msg:data
    })
    res.send({
        code:400,
        title:"登录信息失效",
        msg:err
    })
* @apiSampleRequest http://localhost:5000/api/Post/cart/num
*/

router.post('/Post/cart/num',function(req,res,next){
    let userId = req.body.userId
    let proId = req.body.proId
    let num = req.body.num*1
    
    let token = req.headers.token
    tools.verify(token).then(result => {
        sql.getData(cart,{userId}).then(data => {
            if(data.length > 0){
                let arr = data[0].proData
                let i = 0;
                let onoff = arr.some((val,idx)=>{
                    i = idx
                    return val.proId === proId
                })
                if(onoff){
                    arr[i].num = num
                }
                sql.setData(cart, {userId}, {
                    proData: arr
                }).then(()=>{
                    res.send({
                        code:200,
                        title:"修改购物车数量成功",
                        msg:cartData[0]
                    })
                })
            }else{
                res.send({
                    code:201,
                    title:"没有购物车数据",
                    msg:"no"
                })
            }
        })
    }).catch(err => {
        res.send({
            code:400,
            title:"登录失效",
            msg:err
        })
    })
})


/**
* @apiGroup 购物车信息
* @api {post} /api/Post/cart/flag 修改购物车内的商品状态
* @apiVersion 0.0.0
* @apiDescription 修改购物车内的商品状态
* @apiParam {String} userId 要修改购物车数据的用户id
* @apiParam {String} proId 要修改购物车的商品数据的id
* @apiParam {number} flag 要修改购物车的商品数据的状态
* @apiSuccess {number} code 请求状态
* @apiSuccess {string} title 请求说明
* @apiSuccess {array} msg 请求数据
* @apiSuccessExample {json} Success-Response:
    res.send({
        code:200,
        title:"删除成功",
        msg:data
    })
    res.send({
        code:400,
        title:"登录信息失效",
        msg:err
    })
* @apiSampleRequest http://localhost:5000/api/Post/cart/flag
*/

router.post('/Post/cart/flag',function(req,res,next){
    let userId = req.body.userId
    let proId = req.body.proId
    let flag = req.body.flag?1:0
    
    let token = req.headers.token
    tools.verify(token).then(result => {
        sql.getData(cart,{userId}).then(data => {
            if(data.length > 0){
                let arr = data[0].proData
                let i = 0;
                let onoff = arr.some((val,idx)=>{
                    i = idx
                    return val.proId === proId
                })
                if(onoff){
                    arr[i].flag = flag
                }
                sql.setData(cart, {userId}, {
                    proData: arr
                }).then(()=>{
                    res.send({
                        code:200,
                        title:"修改购物车状态成功",
                        msg:cartData[0]
                    })
                })
            }else{
                res.send({
                    code:201,
                    title:"没有购物车数据",
                    msg:"no"
                })
            }
        })
    }).catch(err => {
        res.send({
            code:400,
            title:"登录失效",
            msg:err
        })
    })
})



/**
* @apiGroup 购物车信息
* @api {post} /api/Post/cart/allFlag 修改购物车内的商品状态
* @apiVersion 0.0.0
* @apiDescription 修改购物车内的商品状态
* @apiParam {String} userId 要获取购物车数据的用户id
* @apiParam {number} flag 要修改购物车的商品数据的状态
* @apiSuccess {number} code 请求状态
* @apiSuccess {string} title 请求说明
* @apiSuccess {array} msg 请求数据
* @apiSuccessExample {json} Success-Response:
    res.send({
        code:200,
        title:"删除成功",
        msg:data
    })
    res.send({
        code:400,
        title:"登录信息失效",
        msg:err
    })
* @apiSampleRequest http://localhost:5000/api/Post/cart/allFlag
*/

router.post('/Post/cart/allFlag',function(req,res,next){
    let userId = req.body.userId
    let flag = req.body.flag?1:0
    
    let token = req.headers.token
    tools.verify(token).then(result => {
        sql.getData(cart,{userId}).then(data => {
            if(data.length > 0){
                let arr = data[0].proData
                arr.forEach(val => {
                    val.flag = flag
                })
                sql.setData(cart, {userId}, {
                    proData: arr
                }).then(()=>{
                    res.send({
                        code:200,
                        title:"修改购物车状态成功",
                        msg:cartData[0]
                    })
                })
            }else{
                res.send({
                    code:201,
                    title:"没有购物车数据",
                    msg:"no"
                })
            }
        })
    }).catch(err => {
        res.send({
            code:400,
            title:"登录失效",
            msg:err
        })
    })
})


/**
* @apiGroup 订单信息
* @api {post} /api/Post/order/add 创建订单
* @apiVersion 0.0.0
* @apiDescription 创建订单
* @apiParam {String} userId 要添加订单的用户id
* @apiParam {Array} proData 要添加到订单的所有的商品数据(含id和num)
* @apiSuccess {number} code 请求状态
* @apiSuccess {string} title 请求说明
* @apiSuccess {array} msg 请求数据
* @apiSuccessExample {json} Success-Response:
    res.send({
        code:200,
        title:"删除成功",
        msg:data
    })
    res.send({
        code:400,
        title:"登录信息失效",
        msg:err
    })
* @apiSampleRequest http://localhost:5000/api/Post/order/add
*/

router.post('/Post/order/add',function(req,res,next){
    let userId = req.body.userId
    let proData = JSON.parse(req.body.proData)
    
    let token = req.headers.token
    tools.verify(token).then(result => {
        (async function(){
            let bigArr = [];
            // 每一个商品id都需要验证是否存在
            // 遍历数组
            for(var i=0;i<proData.length;i++){
                // 验证商品是否存在
                let pd = await sql.getData(pro, {proId: proData[i].proId});
                if(pd.length > 0){
                    bigArr.push({
                        proId: pd[0].proId,
                        img: pd[0].img,
                        proName:pd[0].proName,
                        price:pd[0].price,
                        num:proData[i].num
                    })
                }
            }
            sql.addData(order, {
                orderId: "order-" + uuid.v1(),
                userId,
                proData: bigArr,
                state: 0,
                time:Date.now()
            }).then(()=>{
                sql.getData(cart, {userId}).then(cartData=>{
                    var arr = cartData[0].proData.filter(val=>!val.flag)
                    sql.setData(cart,{userId},{
                        proData:arr
                    }).then(()=>{
                        res.send({
                            code:200,
                            title:"添加订单并删除购物车对应数据成功",
                            msg:"ok"
                        })
                    })
                })
            })
        })();
    }).catch(err => {
        res.send({
            code:400,
            title:"登录失效",
            msg:err
        })
    })
})


/**
* @apiGroup 订单信息
* @api {post} /api/Post/order  获取用户订单
* @apiVersion 0.0.0
* @apiDescription 获取用户订单
* @apiParam {String} userId 要获取订单的用户id
* @apiSuccess {number} code 请求状态
* @apiSuccess {string} title 请求说明
* @apiSuccess {array} msg 请求数据
* @apiSuccessExample {json} Success-Response:
    res.send({
        code:200,
        title:"删除成功",
        msg:data
    })
    res.send({
        code:400,
        title:"登录信息失效",
        msg:err
    })
* @apiSampleRequest http://localhost:5000/api/Post/order
*/
router.post('/Post/order',function(req,res,next){
    let userId = req.body.userId
    let orderId = req.body.orderId
    let token = req.headers.token
    tools.verify(token).then(result =>{
        sql.getData(order, {$or:[{userId},{orderId}]}).then(data=>{
            res.send({
                code:200,
                title:"获取成功",
                msg:data
            })
        })
    }).catch(err => {
        res.send({
            code:400,
            title:"登录失效",
            msg:err
        })
    })
})

/**
* @apiGroup 订单信息
* @api {post} /api/Post/order/pay 去支付
* @apiVersion 0.0.0
* @apiDescription 去支付
* @apiParam {String} userId 要添加订单的用户id
* @apiParam {String} orderId 要添加订单的用户id
* @apiParam {Number} price 订单的总价格(暂无，二期功能)
* @apiSuccess {number} code 请求状态
* @apiSuccess {string} title 请求说明
* @apiSuccess {array} msg 请求数据
* @apiSuccessExample {json} Success-Response:
    res.send({
        code:200,
        title:"请求成功",
        msg:data
    })
* @apiSampleRequest http://localhost:5000/api/Post/order/pay
*/

router.post('/Post/order/pay', function(req, res, next) {
    let userId = req.body.userId
    let orderId = req.body.orderId

    let token = req.headers.token

    tools.verify(token).then(result=>{
        sql.setData(order, {userId, orderId},{
            state: 1
        }).then(()=>{
            res.send({
                code:200,
                title:"支付成功",
                msg:"ok"
            })
        })
    }).catch(err=>{
        res.send({
            code:400,
            title:"登录失效",
            msg:err
        })
    })
})


/**
* @apiGroup 订单信息
* @api {post} /api/Post/order/confirm 确认收货
* @apiVersion 0.0.0
* @apiDescription 确认收货
* @apiParam {String} userId 要确认收货的用户id
* @apiParam {String} orderId 要确认收货的用户id
* @apiParam {Number} price 订单的总价格(暂无，二期功能)
* @apiSuccess {number} code 请求状态
* @apiSuccess {string} title 请求说明
* @apiSuccess {array} msg 请求数据
* @apiSuccessExample {json} Success-Response:
    res.send({
        code:200,
        title:"请求成功",
        msg:data
    })
* @apiSampleRequest http://localhost:5000/api/Post/order/confirm
*/

router.post('/Post/order/confirm', function(req, res, next) {
    let userId = req.body.userId
    let orderId = req.body.orderId

    let token = req.headers.token

    tools.verify(token).then(result=>{
        sql.setData(order, {userId, orderId},{
            state: 3
        }).then(()=>{
            res.send({
                code:200,
                title:"支付成功",
                msg:"ok"
            })
        })
    }).catch(err=>{
        res.send({
            code:400,
            title:"登录失效",
            msg:err
        })
    })
})


/**
* @apiGroup 订单信息
* @api {post} /api/Post/order/idea 去评价
* @apiVersion 0.0.0
* @apiDescription 确认收货
* @apiParam {String} userId 要确认收货的用户id
* @apiParam {String} orderId 要确认收货的用户id
* @apiParam {Number} price 订单的总价格(暂无，二期功能)
* @apiSuccess {number} code 请求状态
* @apiSuccess {string} title 请求说明
* @apiSuccess {array} msg 请求数据
* @apiSuccessExample {json} Success-Response:
    res.send({
        code:200,
        title:"请求成功",
        msg:data
    })
* @apiSampleRequest http://localhost:5000/api/Post/order/idea
*/

router.post('/Post/order/idea', function(req, res, next) {
    let userId = req.body.userId
    let orderId = req.body.orderId

    let token = req.headers.token

    tools.verify(token).then(result=>{
        sql.setData(order, {userId, orderId},{
            state: 4
        }).then(()=>{
            res.send({
                code:200,
                title:"支付成功",
                msg:"ok"
            })
        })
    }).catch(err=>{
        res.send({
            code:400,
            title:"登录失效",
            msg:err
        })
    })
})


/**
* @apiGroup 搜索
* @api {get} /api/Get/search 获取搜索历史
* @apiVersion 0.0.0
* @apiDescription 获取搜索历史
* @apiParam {String} userId 获取搜索历史的用户id
* @apiSuccess {number} code 请求状态
* @apiSuccess {string} title 请求说明
* @apiSuccess {array} msg 请求数据
* @apiSuccessExample {json} Success-Response:
    res.send({
        code:200,
        title:"请求成功",
        msg:data
    })
* @apiSampleRequest http://localhost:5000/api/Get/search
*/
router.post('/Post/search', function(req, res, next) {
    let userId = req.body.userId
    sql.getData(search,{userId}).then(data => {
        res.send({
            code:200,
            title:"获取成功",
            msg:data
        })
    })

})



/**
* @apiGroup 搜索
* @api {post} /api/Post/search/add 添加搜索历史
* @apiVersion 0.0.0
* @apiDescription 添加搜索历史
* @apiParam {String} userId 添加搜索历史的用户id
* @apiParam {String} word 添加搜索内容
* @apiSuccess {number} code 请求状态
* @apiSuccess {string} title 请求说明
* @apiSuccess {array} msg 请求数据
* @apiSuccessExample {json} Success-Response:
    res.send({
        code:200,
        title:"请求成功",
        msg:data
    })
* @apiSampleRequest http://localhost:5000/Post/search/add
*/
router.post('/Post/search/add', function(req, res, next) {
    let userId = req.body.userId
    let word =req.body.word

    let token = req.headers.token;
    tools.verify(token).then(result=>{
        sql.addData(search,{
            userId,
            searchId: "search-" + uuid.v1(),
            searchKey: word,
            time: Date.now()
        }).then(()=>{
            res.send({
                code:200,
                title:"搜索关键字添加成功",
                msg:data
            })
        })
    }).catch(err=>{
        res.send({
            code:400,
            title:"登录信息失效",
            msg:err
        })
    })

   

})

/**
* @apiGroup 搜索
* @api {post} /api/Post/search/del 删除搜索历史
* @apiVersion 0.0.0
* @apiDescription 删除搜索历史
* @apiParam {String} userId 删除搜索历史的用户id
* @apiParam {String} word 删除搜索内容
* @apiSuccess {number} code 请求状态
* @apiSuccess {string} title 请求说明
* @apiSuccess {array} msg 请求数据
* @apiSuccessExample {json} Success-Response:
    res.send({
        code:200,
        title:"请求成功",
        msg:data
    })
* @apiSampleRequest http://localhost:5000/Post/search/del
*/
router.post('/Post/search/del', function(req, res, next) {
    let userId = req.body.userId
    let word =req.body.word
    let token = req.headers.token;
    tools.verify(token).then(result=>{
        sql.delData(search, {
            userId,
            searchKey: word
        }).then(()=>{
            sql.getData(search, {userId}).then((data)=>{
                const searchArr = [];
                data.forEach(val=>{
                    searchArr.push(val.searchKey)
                })
                res.send({
                    code:200,
                    title:"删除并获取关键字成功",
                    msg:[...new Set(searchArr)].reverse()
                })
            })
        })
    }).catch(err=>{
        res.send({
            code:400,
            title:"登录信息失效",
            msg:err
        })
    })
    
})

/**
* @apiGroup 搜索关键字
* @api {get} /api/Get/search 获取搜索关键字
* @apiVersion 0.0.0
* @apiDescription 获取搜索关键字
* @apiParam {String} userId 正在搜索商品的用户id
* @apiSuccess {number} code 请求状态
* @apiSuccess {string} title 请求说明
* @apiSuccess {array} msg 请求数据
* @apiSuccessExample {json} Success-Response:
    res.send({
        code:200,
        title:"请求成功",
        msg:data
    })
* @apiSampleRequest http://localhost:5000/api/Get/search
*/

router.get('/Get/search', function(req, res, next) {
    let userId = req.query.userId;

    let token = req.headers.token;
    tools.verify(token).then(result=>{
        sql.getData(search, {userId}).then((data)=>{
            const searchArr = [];
            data.forEach(val=>{
                searchArr.push(val.searchKey)
            })
            res.send({
                code:200,
                title:"获取关键字成功",
                msg:[...new Set(searchArr)].reverse()
            })
        })
    }).catch(err=>{
        res.send({
            code:400,
            title:"登录信息失效",
            msg:err
        })
    })
});

/**
* @apiGroup 搜索关键字
* @api {get} /api/Get/search/brand 根据品牌搜索商品
* @apiVersion 0.0.0
* @apiDescription 根据品牌搜索商品
* @apiParam {String} sKey 要搜索的品牌
* @apiSuccess {number} code 请求状态
* @apiSuccess {string} title 请求说明
* @apiSuccess {array} msg 请求数据
* @apiSuccessExample {json} Success-Response:
    res.send({
        code:200,
        title:"请求成功",
        msg:data
    })
* @apiSampleRequest http://localhost:5000/api/Get/search/brand
*/

router.get('/Get/search/brand', function(req, res, next) {
    let searchStr = req.query.sKey;

    sql.getData(pro, {
        brand: searchStr
    }).then(data=>{
        res.send({
            code:200,
            title:"请求成功",
            msg:data
        })
    })
});


module.exports=router